package com.nuoye.camera2studydemo;

import android.annotation.SuppressLint;
import android.content.Context;
import android.hardware.camera2.CameraAccessException;
import android.hardware.camera2.CameraCharacteristics;
import android.hardware.camera2.CameraDevice;
import android.hardware.camera2.CameraManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.core.util.Consumer;
import androidx.databinding.DataBindingUtil;
import androidx.fragment.app.Fragment;

import com.google.gson.Gson;
import com.nuoye.camera2studydemo.databinding.FragmentCameramangerBinding;


import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 * 相机管理者的调用。
 */
public class CameraMangerFragment extends Fragment {
    String TAG = "CameraMangerFragment";
    protected CameraManager cameraManager;
    private FragmentCameramangerBinding binding;
    private Handler cameraHandler;
    private HandlerThread cameraThread;
    int torchIndex=0;
    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        binding = DataBindingUtil.inflate(inflater, R.layout.fragment_cameramanger, container, false);
        return binding.getRoot();
    }

    List<ChickConsumer> items = new ArrayList<>();

    @RequiresApi(api = Build.VERSION_CODES.M)
    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        cameraThread = new HandlerThread("cameraThread");
        cameraThread.start();
        cameraHandler = new Handler(cameraThread.getLooper());
        cameraManager = (CameraManager) getContext().getSystemService(Context.CAMERA_SERVICE);
        // 添加监听。
        /**
         * > 如果在调用打开相机之前开启闪光灯，后调用打开相机，闪光灯会关闭。
         * 第一次调用打开相机
         * * onTorchModeUnavailable闪光灯不可用 : 0
         * * onCameraUnavailable相机不可用: 0
         * * onOpened 打开相机: 0
         * 第2次调用打开相机
         * * onDisconnected 相机断开: 0
         * * onTorchModeChanged 闪光灯模式已经更改 : 0  false
         * * onCameraAvailable 可用的相机: 0
         * * onTorchModeUnavailable闪光灯不可用 : 0
         * * onCameraUnavailable相机不可用: 0
         * * onOpened 打开相机: 0
         */
        cameraManager.registerAvailabilityCallback(new CameraManager.AvailabilityCallback() {
            @Override
            public void onCameraAvailable(@NonNull String cameraId) {
                super.onCameraAvailable(cameraId);
                Log.e(TAG, "onCameraAvailable 可用的相机: " + cameraId);
            }

            @Override
            public void onCameraUnavailable(@NonNull String cameraId) {
                super.onCameraUnavailable(cameraId);
                Log.e(TAG, "onCameraUnavailable相机不可用: " + cameraId);
            }

            @Override
            public void onCameraAccessPrioritiesChanged() {
                super.onCameraAccessPrioritiesChanged();
                Log.e(TAG, "onCameraAccessPrioritiesChanged 关于相机访问优先级已更改: ");
            }
        }, cameraHandler);
        cameraManager.registerTorchCallback(new CameraManager.TorchCallback() {
            @Override
            public void onTorchModeUnavailable(@NonNull String cameraId) {
                super.onTorchModeUnavailable(cameraId);
                Log.e(TAG, "onTorchModeUnavailable闪光灯不可用 : " + cameraId);
            }

            @Override
            public void onTorchModeChanged(@NonNull String cameraId, boolean enabled) {
                super.onTorchModeChanged(cameraId, enabled);
                Log.e(TAG, "onTorchModeChanged 闪光灯模式已经更改 : " + cameraId + "  " + enabled);
            }
        }, cameraHandler);
        initChildItem();
        ArrayAdapter<ChickConsumer> adapter = new ArrayAdapter<ChickConsumer>(getContext(), android.R.layout.simple_expandable_list_item_1, items);
        binding.list.setAdapter(adapter);
        binding.list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                try {
                    items.get(position).getConsumer().accept("");
                } catch (Exception e) {

                }

            }
        });
    }

    private void initChildItem() {
        items.add(new ChickConsumer("getCameraIdList", new Consumer<String>() {
            @Override
            public void accept(String s) {
                try {
                    String[] cameraIdList = cameraManager.getCameraIdList();
                    Log.e(TAG, "accept: " + new Gson().toJson(cameraIdList));
                } catch (CameraAccessException e) {
                    e.printStackTrace();
                }
            }
        }));
        items.add(new ChickConsumer("getConcurrentCameraIds(30才加的api,版本太低会崩溃)", new Consumer<String>() {

            @Override
            public void accept(String s) {
                Set<Set<String>> concurrentCameraIds = null;
//                try {
//                    //30才加的api,版本太低会崩溃
////                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
////                        concurrentCameraIds = cameraManager.getConcurrentCameraIds();
////                        Log.e(TAG, "accept: " + new Gson().toJson(concurrentCameraIds));
////                    }
//                } catch (CameraAccessException e) {
//                    e.printStackTrace();
//                }

            }
        }));
        items.add(new ChickConsumer("查询摄像头设备的能力。", new Consumer<String>() {
            @Override
            public void accept(String s) {
                try {
                    CameraCharacteristics characteristics = cameraManager.getCameraCharacteristics("0");
                    Log.e(TAG, "accept: " + new Gson().toJson(characteristics));
                } catch (CameraAccessException e) {
                    e.printStackTrace();
                }
            }
        }));
        items.add(new ChickConsumer("查询摄像头设备的摄像头扩展能力(31采用)", new Consumer<String>() {
            @Override
            public void accept(String s) {

            }
        }));
        items.add(new ChickConsumer("返回与 cameraId 关联的闪光灯单元的亮度级别(Android 13中添加)", new Consumer<String>() {
            @Override
            public void accept(String s) {

            }
        }));
        items.add(new ChickConsumer("在不打开相机设备的情况下设置给定ID相机的闪光灯单元的手电筒模式(打开闪光灯0)", new Consumer<String>() {
            @Override
            public void accept(String s) {
                try {
                    cameraManager.setTorchMode("0",true);
                } catch (CameraAccessException e) {
                    e.printStackTrace();
                }
            }
        }));
        items.add(new ChickConsumer("在不打开相机设备的情况下设置给定ID相机的闪光灯单元的手电筒模式(关闭闪光灯0)", new Consumer<String>() {
            @Override
            public void accept(String s) {
                try {
                    cameraManager.setTorchMode("0",false);
                } catch (CameraAccessException e) {
                    e.printStackTrace();
                }
            }
        }));
        items.add(new ChickConsumer("打开闪光灯", new Consumer<String>() {
            @Override
            public void accept(String s) {
                try {
                    String[] cameraIdList = cameraManager.getCameraIdList();
                    cameraManager.setTorchMode(cameraIdList[torchIndex/cameraIdList.length],true);
                    torchIndex++;
                } catch (CameraAccessException e) {
                    e.printStackTrace();
                }
            }
        }));
        items.add(new ChickConsumer("在手电筒模式下设置与给定 cameraId 关联的手电筒的亮度级别。(Android 13)", new Consumer<String>() {
            @Override
            public void accept(String s) {

            }
        }));
        items.add(new ChickConsumer("打开相机", new Consumer<String>() {
            @SuppressLint("MissingPermission")
            @Override
            public void accept(String s) {
                try {
                    cameraManager.openCamera("0", new CameraDevice.StateCallback() {
                        @Override
                        public void onOpened(@NonNull CameraDevice cameraDevice) {
                            Log.e(TAG, "onOpened 打开相机: "+cameraDevice.getId() );
                        }

                        @Override
                        public void onDisconnected(@NonNull CameraDevice cameraDevice) {
                            Log.e(TAG, "onDisconnected 相机断开: "+cameraDevice.getId() );
                        }

                        @Override
                        public void onError(@NonNull CameraDevice cameraDevice, int i) {
                            Log.e(TAG, "onDisconnected 发生了错误: "+cameraDevice.getId()+"  "+i );
                        }
                    },cameraHandler);
                } catch (CameraAccessException e) {
                    e.printStackTrace();
                }
            }
        }));


    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        cameraThread.quitSafely();
        try {
            cameraThread.join();
        } catch (Exception e) {

        }
    }
}
